import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:projectfluttershengyihuatong/route.dart';
import 'package:projectfluttershengyihuatong/service/loginService/logginservice.dart';
class RequestManager {
  /// 单例对象
  static RequestManager? _instance;

  /// 内部构造方法，可避免外部暴露构造函数，进行实例化
  RequestManager._internal();

  /// 工厂构造方法，这里使用命名构造函数方式进行声明
  factory RequestManager.getInstance() => _getInstance();
  ///网络请求三方库
  final dio = Dio();
  /// 获取单例内部方法
  static _getInstance() {
    // 只能有一个实例
    if (_instance == null) {
      _instance = RequestManager._internal();
      _instance?.dio.options.baseUrl = "https://test.sharedyxy.com";
      _instance?.dio.options.connectTimeout = const Duration(seconds: 5);
      _instance?.dio.options.receiveTimeout = const Duration(seconds: 5);
      _instance?.dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
        if (kDebugMode) {
          // print("\n================== 请求数据 ==========================");
          // print("url = ${options.uri.toString()}");
          // print("headers = ${options.headers}");
          // print("params = ${options.data}");
        }

        return handler.next(options);
      }, onResponse: (response, handler) {
        if (kDebugMode) {
          print("\n================== 响应数据 ==========================");
          print("url = ${response.requestOptions.uri.toString()}");
          print("params = ${response.requestOptions.queryParameters}");
          print("headers = ${response.requestOptions.headers}");

          print("code = ${response.statusCode}");
          print("data = ${response.data}");
          print("\n");
        }

        final ret = response.data["ret"] as int;
        if (ret == 10) {
          Future.delayed(Duration(milliseconds: 1000)).then((value){
            Get.toNamed(RouteNames.LOGIN);
          });
        }


        handler.next(response);
      }, onError: (DioException e, handler) {
        if (kDebugMode) {
          print("\n================== 错误响应数据 ======================");
          print("type = ${e.type}");
          print("message = ${e.message}");
          print("\n");
        }

        return handler.next(e);
      }));
    }
    final token = LoginService.getInstance().userInfo?.token ?? "";
    if (token.isNotEmpty) {
      _instance?.dio.options.headers["token"] = token;
    }



    return _instance;
  }




}


